package com.microtf.wx.server;

import com.microtf.wx.server.entity.BodySeg;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class BaiduAPI {
    Logger logger= LoggerFactory.getLogger(BaiduAPI.class);
    @Value("${baidu.api.key}")
    String api;
    @Value("${baidu.api.secret}")
    String sk;
    @Autowired
    OkHttpClient okHttpClient;

    private BaiduApiToken baiduApiToken = null;


    private void updateToken() {
        if (baiduApiToken != null) {
            Calendar c = Calendar.getInstance();
            c.setTime(baiduApiToken.getCreateData());
            c.add(Calendar.DATE, 4);

            if (new Date().before(c.getTime())) {
                return;
            }
        }
        String apiUrl = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={client_id}&&client_secret={client_secret}";//


        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("client_id", api);
        hashMap.put("client_secret", sk);
        NetClient netClient = new NetClient(okHttpClient);
        netClient.setUrl(apiUrl, hashMap);
        baiduApiToken = netClient.requestToOjbect(BaiduApiToken.class);
        System.out.println(this.baiduApiToken);
        this.baiduApiToken.setCreateData(new Date());
    }

    private String getToken() {
        if (baiduApiToken != null) {
            Calendar c = Calendar.getInstance();
            c.setTime(baiduApiToken.getCreateData());
            c.add(Calendar.DATE, 4);

            if (new Date().before(c.getTime())) {
                updateToken();
                return baiduApiToken.getAccessToken();
            }
        }
        updateToken();
        return baiduApiToken.getAccessToken();
    }

    /**
     * 图片文字识别
     *
     * @param file 文件路径
     * @return 图片识别结果
     */
    public String getPicInfo(String file) {
        String apiUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/general?access_token={access_token}";//
        NetClient netClient = new NetClient(okHttpClient);

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("access_token", getToken());
        netClient.setUrl(apiUrl, hashMap);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        Map<String, String> postMap = new HashMap<>();
        try {
            BufferedImage image = ImageIO.read(new File(file));
            int width = image.getWidth();
            int height = image.getHeight();
            BufferedImage grayImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);//重点，技巧在这个参数BufferedImage.TYPE_BYTE_GRAY
            Graphics graphics = grayImage.getGraphics();
            graphics.drawImage(image,0,0,width,height,null);

            ImageIO.write(grayImage, "jpg", byteArrayOutputStream);
            postMap.put("image",String.valueOf(Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray())));
        } catch (IOException e) {
            logger.warn("读取用户图片出错");
            return "{\"error\":\"读取用户图片出错\"}";
        }
        netClient.setPostMap(postMap);
        return netClient.requestToString();
    }

    /**
     * 用户人像扣图
     *
     * @param file
     * @return
     */
    public BodySeg bodySeg(String file) {
        String apiUrl = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg?access_token={access_token}";//
        NetClient netClient = new NetClient(okHttpClient);

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("access_token", getToken());
        netClient.setUrl(apiUrl, hashMap);
        byte[] bytes = new byte[0];
        try {
            bytes = Files.readAllBytes(Paths.get(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, String> postMap = new HashMap<>();
        postMap.put("image", String.valueOf(Base64.getEncoder().encodeToString(bytes)));
        postMap.put("type", "foreground");
        netClient.setPostMap(postMap);
        return netClient.requestToOjbect(BodySeg.class);
    }
    /**
     * 身份证识别
     *
     * @param file
     * @return
     */
    public String idCard(String file,String id_card_side) {
        String apiUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={access_token}";//
        NetClient netClient = new NetClient(okHttpClient);

        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("access_token", getToken());
        netClient.setUrl(apiUrl, hashMap);
        byte[] bytes = new byte[0];
        try {
            bytes = Files.readAllBytes(Paths.get(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map<String, String> postMap = new HashMap<>();
        postMap.put("image", String.valueOf(Base64.getEncoder().encodeToString(bytes)));
        postMap.put("id_card_side", id_card_side);
        postMap.put("detect_direction", "true");
        postMap.put("detect_risk", "true");

        netClient.setPostMap(postMap);
        return netClient.requestToString();
    }
}
